import { getSpotMartetZcqReqInfo } from "../../generate"
import { reactive, ref } from 'vue'
import { ElMessage, dayjs, type FormRules } from 'element-plus'

import { AsyncRecursion, creatAsyncRecursion } from '@src/utils/asyncRecursion'
import { promisetTimeOut } from '@src/utils/common'
import { betweenStartEndDays } from "../../generate"

import type { RuleForm } from './type'
import { getRollDataHandle } from "@src/spotZcqMarketPublic/dayRollMatch/dayRollTrade";

export const usePrivateData = (ruleFormRef:any) => {

  const loading = ref(false)

  const reqHistory = ref<{ certainDate: string, reqTypes: string }[]>([])

  const ruleForm = reactive<RuleForm>({
    certainDate: [dayjs().startOf('month').format('YYYY-MM-DD'), dayjs().endOf('month').format('YYYY-MM-DD')],
    uniqueCode:''
  })

  const validateUniqueCode = (rule: any, value: any, callback: any) => {
    if (String(value).toLowerCase() !== 'hd2024') {
      callback(new Error('验证码输入错误'))
    } else {
      callback()
    }
  }
  const rules = reactive<FormRules<RuleForm>>({
    certainDate: [
      { required: true, message: '请选择数据日期', trigger: 'blur' },
    ],
    uniqueCode: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur',
      },
      { validator: validateUniqueCode, trigger: 'blur' }
    ]
  })

  let pickedStartDate:Date | null = null
  const calendarChange = (pickedDate:Date[]) => {
    const [min, max] = pickedDate
    if (max) {
      pickedStartDate = null
    } else {
      pickedStartDate = min
    }
  }

  /** 最多选择10天的时间 */
  const disabledDate = (date: Date) => {
    const appEnv = import.meta.env.VITE_APP_ENV
    if(/^dev/.test(appEnv)) return false
    
    const theTime = date.getTime()

    if (!pickedStartDate) return false

    const minDate = dayjs(pickedStartDate).subtract(186, 'day').valueOf()
    const maxDate = dayjs(pickedStartDate).add(186, 'day').valueOf()

    return theTime < minDate || theTime > maxDate
  }

  /** 保存请求成功历史 */
  const setReqHistory = (certainDate:string) => {
    reqHistory.value.unshift({
      certainDate,
      reqTypes: '私有数据'
    })
  }

    /** 请求一天的数据 */
    const reqOneCertainDateData = async ({headers, unitid, certainDate}:{headers:HeadersInit,unitid:string,certainDate:string}) => {
      try {
        await getRollDataHandle({headers, unitid, certainDate})
        setReqHistory(certainDate)
      }catch(e) {
        console.error(e)
        ElMessage.error('获取数据失败！ 请刷新主系统和子系统后重试')
      }
    }
  
    const reqData = async () => {
      try {
        loading.value = true

       const {headers, unitid} = await getSpotMartetZcqReqInfo()
      
        await creatAsyncRecursion(AsyncRecursion, {
          stepAsyncFnParamsList: betweenStartEndDays(ruleForm.certainDate[0], ruleForm.certainDate[1]).map(certainDate => ({certainDate, headers, unitid})),
          stepAsyncFn: reqOneCertainDateData,
          stepCb: async () => await promisetTimeOut(1000), // 每天延时 1s
          stepAsyncNum: 1,
          errBreak: false
        }).start()
  
        ElMessage.warning('获取数据结束')
      }catch(e) {
        console.error(e)
        ElMessage.error('获取数据失败！ 请刷新主系统和子系统后重试')
      }finally {
        loading.value = false
      }
    }


  const submitForm = async () => {
    if (!ruleFormRef?.value) return
    // if(!validateTimeMinute()) return
    await ruleFormRef.value.validate()
    reqData()
  }

  const resetForm = () => {
    if (!ruleFormRef?.value) return
    ruleFormRef.value.resetFields()
  }

  return {
    loading,
    ruleForm,
    rules,
    submitForm,
    resetForm,
    reqHistory,
    disabledDate,
    calendarChange
  }
}